package com.lzyyj.gmis.base.dao.hibernate;

import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.type.Type;

import java.util.Iterator;

/**
 * Hack the original class
 * 2012-04-10
 * @author wangzhen
 * 
 */
public class SQLCriterion implements Criterion {
	private static final long	serialVersionUID	= 561456879784847643L;
	private final String sql;
	private final TypedValue[] typedValues;

	public String toSqlString(
		Criteria criteria,
		CriteriaQuery criteriaQuery)
	throws HibernateException {
		CriteriaImpl rootCriteria = null;
		if(criteria instanceof CriteriaImpl){
			rootCriteria = (CriteriaImpl)criteria;
		}else if(criteria instanceof CriteriaImpl.Subcriteria){
			rootCriteria = (CriteriaImpl) ((CriteriaImpl.Subcriteria)criteria).getParent();
		}else {
			throw new HibernateException("暂不支持其他Criteria的实现");
		}
		Iterator iterateSubcriteria = rootCriteria.iterateSubcriteria();
		String tempSql = sql;
		//replace subcriterias' alias
		while (iterateSubcriteria.hasNext()) {
			CriteriaImpl.Subcriteria subCriteria = (CriteriaImpl.Subcriteria) iterateSubcriteria.next();
			tempSql = StringHelper.replace( tempSql, "{"+subCriteria.getAlias()+"}", criteriaQuery.getSQLAlias(subCriteria) );
		}
		return StringHelper.replace( tempSql, "{alias}", criteriaQuery.getSQLAlias(criteria) );
	}

	public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery)
	throws HibernateException {
		return typedValues;
	}

	public String toString() {
		return sql;
	}

	public SQLCriterion(String sql, Object[] values, Type[] types) {
		this.sql = sql;
		typedValues = new TypedValue[values.length];
		for ( int i=0; i<typedValues.length; i++ ) {
			typedValues[i] = new TypedValue( types[i], values[i], EntityMode.POJO );
		}
	}
}